import json
import os
import tkinter as tk
from pathlib import Path
from tkinter import messagebox

# version:2.4.5
dictionary = {
    'fg': '#ffffff',
    'Button_bg': '#060606',
    'Button_bg_num': '#015ca1',
    'Button_bg_notice': '#7715BF',
    'Button_bg_fun': '#3a9583',
    'Button_active_bg': '#2E2E2E',
    'Button_active_fg': '#ffffff',
    'width': 365,
    'height': 275,
    'autosize': True,
    'topmost': True,
}
path = Path('settings.json')
if path.exists():
    contents = path.read_text()
    dictionary = json.loads(contents)
else:
    contents = json.dumps(dictionary,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ':'))
    path.write_text(contents)
font_show = ('黑体', 20)
font_button = ('黑体', 16)  # 设置全局按键字体字号
root = tk.Tk()
root.title('普通计算器')  # 设置标题
root.resizable(0, 0)  # 禁止调整窗口大小


def moreinfo():
    os.system(
        'start https://gitee.com/TuChenjia/my-python/tree/master/%E8%AE%A1%E7%AE%97%E5%99%A8'
    )


def showinfo():
    messagebox.showinfo(title='关于', message='软件名称：计算器\n作者：TCJ\n版本号：2.4.5')


menubar = tk.Menu(root)
aboutmenu = tk.Menu(menubar, tearoff=False)
aboutmenu.add_command(label='软件信息', command=showinfo)
aboutmenu.add_command(label='源代码网页', command=moreinfo)
menubar.add_cascade(label='关于', menu=aboutmenu)
root.config(menu=menubar)
try:
    if dictionary['autosize'] == True:
        pass
    else:
        root.geometry(
            str(dictionary['width']) + 'x' + str(dictionary['height']))
    if dictionary['topmost'] == True:
        root.attributes('-topmost', 'true')
    else:
        root.attributes('-topmost', 'false')
    root["background"] = "#393939"  # 设置bg颜色
    fg = dictionary['fg']
    Button_bg = dictionary['Button_bg']  # M系列按钮bg
    Button_bg_num = dictionary['Button_bg_num']  # 数字键bg
    Button_bg_notice = dictionary['Button_bg_notice']  # 警示建bg
    Button_bg_fun = dictionary['Button_bg_fun']  # 功能键bg
    Button_active_bg = dictionary['Button_active_bg']  # 按压bg
    Button_active_fg = dictionary['Button_active_fg']  # 按压fg
except KeyError as e:
    messagebox.showwarning(
        '个性化定义出错',
        '你的自定义文件settings.json中没有定义完全\n需要包含：fg, Button_bg, Button_bg_notice, BUtton_bg_fun, Button_active_bg, '
        'Button_active_fg, width, height, autosize, topmost\n删除掉源文件并重启应用程序即可解决问题'
    )
    dictionary = {
        'fg': '#ffffff',
        'Button_bg': '#060606',
        'Button_bg_num': '#015ca1',
        'Button_bg_notice': '#7715BF',
        'Button_bg_fun': '#3a9583',
        'Button_active_bg': '#2E2E2E',
        'Button_active_fg': '#ffffff',
        'width': 365,
        'height': 275,
        'autosize': True,
        'topmost': True,
    }
    root["background"] = "#393939"
    fg = dictionary['fg']
    Button_bg = dictionary['Button_bg']
    Button_bg_num = dictionary['Button_bg_num']
    Button_bg_notice = dictionary['Button_bg_notice']
    Button_bg_fun = dictionary['Button_bg_fun']
    Button_active_bg = dictionary['Button_active_bg']
    Button_active_fg = dictionary['Button_active_fg']
    if dictionary['topmost'] == True:
        root.attributes('-topmost', 'true')
    else:
        root.attributes('-topmost', 'false')
# 定义显示区
result_num = tk.StringVar()
result_num.set('')
tk.Label(root,
         textvariable=result_num,
         font=font_show,
         height=2,
         width=25,
         justify=tk.LEFT,
         bg='#393939',
         fg='#ffffff',
         anchor=tk.SE).grid(row=1, column=1, columnspan=5)
# 定义第一排按键
button_left = tk.Button(root,
                        text="(",
                        width=12,
                        font=font_button,
                        relief=tk.FLAT,
                        bg=Button_bg,
                        activebackground=Button_active_bg,
                        activeforeground=Button_active_fg,
                        fg=fg)
button_right = tk.Button(root,
                         text=")",
                         width=12,
                         font=font_button,
                         relief=tk.FLAT,
                         bg=Button_bg,
                         activebackground=Button_active_bg,
                         activeforeground=Button_active_fg,
                         fg=fg)
button_left.grid(row=2, column=1, padx=4, pady=2, columnspan=2)
button_right.grid(row=2, column=3, padx=4, pady=2, columnspan=2)
# 定义第二行按钮
button_7 = tk.Button(root,
                     text="7",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_8 = tk.Button(root,
                     text="8",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_9 = tk.Button(root,
                     text="9",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_del = tk.Button(root,
                       text="DEL",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_notice,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_AC = tk.Button(root,
                      text="AC",
                      width=5,
                      font=font_button,
                      relief=tk.FLAT,
                      bg=Button_bg_notice,
                      activebackground=Button_active_bg,
                      activeforeground=Button_active_fg,
                      fg=fg)
button_7.grid(row=3, column=1, padx=4, pady=2)
button_8.grid(row=3, column=2, padx=4, pady=2)
button_9.grid(row=3, column=3, padx=4, pady=2)
button_del.grid(row=3, column=4, padx=4, pady=2)
button_AC.grid(row=3, column=5, padx=4, pady=2)
# 定义第三行按钮
button_4 = tk.Button(root,
                     text="4",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_5 = tk.Button(root,
                     text="5",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_6 = tk.Button(root,
                     text="6",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_mul = tk.Button(root,
                       text="×",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_fun,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_div = tk.Button(root,
                       text="÷",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_fun,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_4.grid(row=4, column=1, padx=4, pady=2)
button_5.grid(row=4, column=2, padx=4, pady=2)
button_6.grid(row=4, column=3, padx=4, pady=2)
button_mul.grid(row=4, column=4, padx=4, pady=2)
button_div.grid(row=4, column=5, padx=4, pady=2)
# 定义第四行按钮
button_1 = tk.Button(root,
                     text="1",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_2 = tk.Button(root,
                     text="2",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_3 = tk.Button(root,
                     text="3",
                     width=5,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_add = tk.Button(root,
                       text="+",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_fun,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_sub = tk.Button(root,
                       text="-",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_fun,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_1.grid(row=5, column=1, padx=4, pady=2)
button_2.grid(row=5, column=2, padx=4, pady=2)
button_3.grid(row=5, column=3, padx=4, pady=2)
button_add.grid(row=5, column=4, padx=4, pady=2)
button_sub.grid(row=5, column=5, padx=4, pady=2)
# 定义第五行按钮
button_0 = tk.Button(root,
                     text="0",
                     width=12,
                     font=font_button,
                     relief=tk.FLAT,
                     bg=Button_bg_num,
                     activebackground=Button_active_bg,
                     activeforeground=Button_active_fg,
                     fg=fg)
button_dot = tk.Button(root,
                       text=".",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_num,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_per = tk.Button(root,
                       text="%",
                       width=5,
                       font=font_button,
                       relief=tk.FLAT,
                       bg=Button_bg_fun,
                       activebackground=Button_active_bg,
                       activeforeground=Button_active_fg,
                       fg=fg)
button_equal = tk.Button(root,
                         text="=",
                         width=5,
                         font=font_button,
                         relief=tk.FLAT,
                         bg=Button_bg_fun,
                         fg=fg)
button_0.grid(row=6, column=1, padx=4, pady=2, columnspan=2)
button_dot.grid(row=6, column=3, padx=4, pady=2)
button_per.grid(row=6, column=4, padx=4, pady=2)
button_equal.grid(row=6, column=5, padx=4, pady=2)


# 定义按动事件
def button_click(x):
    result_num.set(result_num.get() + x)


def calculate():
    previous_str = result_num.get()
    try:
        result_num.set(str(eval(previous_str)))
        A = result_num.get()
    except Exception as e:
        messagebox.showwarning("出错啦", f"错误内容{e}")


def backspace():
    if len(result_num.get()) >= 1:
        result_num.set(result_num.get()[:-1])
    else:
        result_num.set('')


def cleannum():
    result_num.set('')


def deletehistory():
    with open('./history.txt', 'w') as hist:
        hist.write('')


button_1.config(command=lambda: button_click('1'))
button_2.config(command=lambda: button_click('2'))
button_3.config(command=lambda: button_click('3'))
button_4.config(command=lambda: button_click('4'))
button_5.config(command=lambda: button_click('5'))
button_6.config(command=lambda: button_click('6'))
button_7.config(command=lambda: button_click('7'))
button_8.config(command=lambda: button_click('8'))
button_9.config(command=lambda: button_click('9'))
button_0.config(command=lambda: button_click('0'))
button_add.config(command=lambda: button_click('+'))
button_sub.config(command=lambda: button_click('-'))
button_mul.config(command=lambda: button_click('*'))
button_div.config(command=lambda: button_click('/'))
button_per.config(command=lambda: button_click('%'))
button_left.config(command=lambda: button_click('('))
button_right.config(command=lambda: button_click(')'))
button_equal.config(command=calculate)
button_AC.config(command=cleannum)
root.mainloop()
